const {
  rootPath,
  API,
  HomePath
} = require("../../utils/const")
const {
  postLogin,
  getRequest,
  requestUserInfo
} = require("../../utils/request")

const dateUtils = require("../../utils/dateUtils")

Page({
  data: {
    agreementLetter: {},
    agreementLetterBaseInfo: {},
    equipments: [],
    signatureUrl: '',
    loginType: ''
  },

  navigateToVideo: function() {
    const videoUrl = encodeURIComponent(this.data.agreementLetterBaseInfo.video);
    wx.navigateTo({
      url: '/pages/videoPlayer/videoPlayer?url=' + videoUrl
    });
  },

  onLoad: function(options) {
    const agreementId = options.id;
    const loginType = wx.getStorageSync('loginType');
    this.setData({
      loginType: loginType
    });

    this.fetchAgreementLetterDetail(agreementId);  
  },

  fetchAgreementLetterDetail: function(id) {
    const that = this;
    getRequest(API.getAgreementLetterById + '/' + id).then(res => {
      that.setData({
        agreementLetter: res
      }, () => {
        let hasSigned = that.data.agreementLetter.hasSigned;
        if (hasSigned) {
          let signedName = that.data.agreementLetter.signedName;
          signedName = signedName.replace(/\\/g, '/');
          that.setData({
            signatureUrl: rootPath + signedName
          });

          console.log(that.data.signatureUrl);
        }

        const letterId = that.data.agreementLetter.letterId;
        getRequest(API.getAgreementLetterBaseInfoById + '/' + letterId).then(resplus => {
          that.setData({
            agreementLetterBaseInfo: resplus
          });
        });

        const agreementLetter = that.data.agreementLetter;
        agreementLetter.sendTime = dateUtils.formatComplaintTime(agreementLetter.sendTime);
        that.setData({
          agreementLetter: agreementLetter
        });

        const medicalEquipments = JSON.parse(that.data.agreementLetter.medicalEquipments);

        const requests = medicalEquipments.map(id =>
          getRequest(API.getMedicalEquipmentById + '/' + id)
        );

        // 等待所有请求完成
        Promise.all(requests)
        .then(responses => {
          // `responses` 是所有请求的结果数组
          const equipmentList = responses.map(response => response); // 根据实际的响应结构取数据
          this.setData({
            equipments: equipmentList
          });

          console.log('Fetched equipment details:', equipmentList);
        })
        .catch(error => {
          console.error('Error fetching equipment details:', error);
        });
      });
    })
    .catch(error => {
      console.error('Error fetching agreement letter:', error);
    });
  },

  onSubmit() {
    if (!this.data.agreementLetter.hasSigned) {
      wx.navigateTo({
        url: `/pages/signName/signName?id=${this.data.agreementLetter.agreementId}`,
      })
    }
  }
});